<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="Location 对象location 是最有用的BOM对象之一，它提供了与当前窗口中加载的文档有关的信息，还提供了一些导航功能。location 对象是很特别的一个对象，因为它既是window 对象的属性，也是document 对象的属性。
window.location 和document.location 引用的是同一个对象。location 对象的用处不只表现在它保存着当前文档的信息，还表">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第八章-2">
<meta property="og:url" content="http://codingme.xyz/2016/09/30/javascript-note-08-2/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="Location 对象location 是最有用的BOM对象之一，它提供了与当前窗口中加载的文档有关的信息，还提供了一些导航功能。location 对象是很特别的一个对象，因为它既是window 对象的属性，也是document 对象的属性。
window.location 和document.location 引用的是同一个对象。location 对象的用处不只表现在它保存着当前文档的信息，还表">
<meta property="og:updated_time" content="2016-10-18T06:23:42.127Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第八章-2">
<meta name="twitter:description" content="Location 对象location 是最有用的BOM对象之一，它提供了与当前窗口中加载的文档有关的信息，还提供了一些导航功能。location 对象是很特别的一个对象，因为它既是window 对象的属性，也是document 对象的属性。
window.location 和document.location 引用的是同一个对象。location 对象的用处不只表现在它保存着当前文档的信息，还表">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/09/30/javascript-note-08-2/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第八章-2 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/09/30/javascript-note-08-2/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第八章-2
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Location-对象"><a href="#Location-对象" class="headerlink" title="Location 对象"></a>Location 对象</h1><p>location 是最有用的BOM对象之一，它提供了与当前窗口中加载的文档有关的信息，还提供了一些导航功能。<br>location 对象是很特别的一个对象，因为它既是window 对象的属性，也是document 对象的属性。</p>
<p>window.location 和document.location 引用的是同一个对象。<br>location 对象的用处不只表现在它保存着当前文档的信息，还表现在它将URL 解析为独立的片段，让开发人员可以通过不同的属性访问这些片段。</p>
<pre><code>hash &quot;#contents&quot; 返回URL中的hash(#号后跟零或多个字符)，如果URL中不包含散列，则返回空字符串
host &quot;www.wrox.com:80&quot; 返回服务器名称和端口号(如果有)
hostname &quot;www.wrox.com&quot; 返回不带端口号的服务器名称
href &quot;http:/www.wrox.com&quot; 返回当前加载页面的完整URL。而location对象的
toString()方法也返回这个值
pathname &quot;/WileyCDA/&quot; 返回URL中的目录和(或)文件名
port &quot;8080&quot; 返回URL中指定的端口号。如果URL中不包含端口号，则
这个属性返回空字符串
protocol &quot;http:&quot; 返回页面使用的协议。通常是http:或https:
search &quot;?q=JavaScript&quot; 返回URL的查询字符串。这个字符串以问号开头
</code></pre><a id="more"></a>
<h2 id="查询字符串参数"><a href="#查询字符串参数" class="headerlink" title="查询字符串参数"></a>查询字符串参数</h2><p>尽管location.search 返回从问号到URL 末尾的所有内容，但却没有办法逐个访问其中的每个查询字符串参数。<br>为此，可以创建一个函数，用以解析查询字符串，然后返回包含所有参数的一个对象：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">getQueryStringArgs</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="comment">//取得查询字符串并去掉开头的问号</span></div><div class="line">    <span class="keyword">var</span> qs = (location.search.length &gt; <span class="number">0</span> ? location.search.substring(<span class="number">1</span>) : <span class="string">""</span>),</div><div class="line">    <span class="comment">//保存数据的对象</span></div><div class="line">    args = &#123;&#125;,</div><div class="line">    <span class="comment">//取得每一项</span></div><div class="line">    items = qs.length ? qs.split(<span class="string">"&amp;"</span>) : [],</div><div class="line">    item = <span class="literal">null</span>,</div><div class="line">    name = <span class="literal">null</span>,</div><div class="line">    value = <span class="literal">null</span>,</div><div class="line">    <span class="comment">//在for 循环中使用</span></div><div class="line">    i = <span class="number">0</span>,</div><div class="line">    len = items.length;</div><div class="line">    <span class="comment">//逐个将每一项添加到args 对象中</span></div><div class="line">    <span class="keyword">for</span> (i=<span class="number">0</span>; i &lt; len; i++)&#123;</div><div class="line">        item = items[i].split(<span class="string">"="</span>);</div><div class="line">        name = <span class="built_in">decodeURIComponent</span>(item[<span class="number">0</span>]);</div><div class="line">        value = <span class="built_in">decodeURIComponent</span>(item[<span class="number">1</span>]);</div><div class="line">        <span class="keyword">if</span> (name.length) &#123;</div><div class="line">            args[name] = value;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> args;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="comment">//假设查询字符串是?q=JavaScript&amp;num=10</span></div><div class="line"><span class="keyword">var</span> args = getQueryStringArgs();</div><div class="line">alert(args[<span class="string">"q"</span>]); <span class="comment">//"JavaScript"</span></div><div class="line">alert(args[<span class="string">"num"</span>]); <span class="comment">//"10"</span></div></pre></td></tr></table></figure>
<h2 id="位置操作"><a href="#位置操作" class="headerlink" title="位置操作"></a>位置操作</h2><p>使用location 对象可以通过很多方式来改变浏览器的位置。<br>最常用的方式，就是使用assign()方法并为其传递一个URL。<br><code>location.assign(&quot;http://www.wrox.com&quot;);</code><br>这样就可以立即打开新URL 并在浏览器的历史记录中生成一条记录。<br>如果是将location.href或window.location 设置为一个URL 值，也会以该值调用assign()方法。<br>最常用的是设置location.href 属性。<br>修改location 对象的其他属性也可以改变当前加载的页面。<br>每次修改location 的属性(hash 除外)，页面都会以新URL 重新加载。</p>
<p>当通过上述任何一种方式修改URL 之后，浏览器的历史记录中就会生成一条新记录，因此用户通过单击“后退”按钮都会导航到前一个页面。<br>要禁用这种行为，可以使用replace()方法。<br>只接受一个参数，即要导航到的URL；结果虽然会导致浏览器位置改变，但不会在历史记录中生成新记录。<br>在调用replace()方法之后，用户不能回到前一个页面。</p>
<p>与位置有关的最后一个方法是reload()，作用是重新加载当前显示的页面。<br>如果调用reload()时不传递任何参数，页面就会以最有效的方式重新加载。<br>也就是说，如果页面自上次请求以来并没有改变过，页面就会从浏览器缓存中重新加载。<br>如果要强制从服务器重新加载，则需要为该方法传递参数true。</p>
<h2 id="navigator-对象"><a href="#navigator-对象" class="headerlink" title="navigator 对象"></a>navigator 对象</h2><p>最早由Netscape Navigator 2.0 引入的navigator 对象，现在已经成为识别客户端浏览器的事实标准。<br>其他浏览器也通过其他方式提供了相同或相似的信息(例如，IE 中的window.clientInformation和Opera 中的window.opera)，<br>但navigator 对象却是所有支持JavaScript 的浏览器所共有的。<br>每个浏览器中的navigator 对象也都有一套自己的属性。不同浏览器版本有不同支持。</p>
<h3 id="检测插件"><a href="#检测插件" class="headerlink" title="检测插件"></a>检测插件</h3><p>对于非IE 浏览器，可以使用plugins 数组来达到这个目的。<br>数组每一项都包含：</p>
<ul>
<li>name：插件的名字。</li>
<li>description：插件的描述。</li>
<li>filename：插件的文件名。</li>
<li>length：插件所处理的MIME 类型数量。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//检测插件(在IE 中无效)</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasPlugin</span>(<span class="params">name</span>)</span>&#123;</div><div class="line">    name = name.toLowerCase();</div><div class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i=<span class="number">0</span>; i &lt; navigator.plugins.length; i++)&#123;</div><div class="line">        <span class="keyword">if</span> (navigator. plugins [i].name.toLowerCase().indexOf(name) &gt; <span class="number">-1</span>)&#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">&#125;</div><div class="line"><span class="comment">//检测Flash</span></div><div class="line">alert(hasPlugin(<span class="string">"Flash"</span>));</div><div class="line"><span class="comment">//检测QuickTime</span></div><div class="line">alert(hasPlugin(<span class="string">"QuickTime"</span>));</div></pre></td></tr></table></figure>
<p>每个插件对象本身也是一个MimeType 对象的数组，这些对象可以通过方括号语法来访问。<br>每个MimeType 对象有4 个属性：包含MIME 类型描述的description、回指插件对象的enabledPlugin、<br>表示与MIME 类型对应的文件扩展名的字符串suffixes(以逗号分隔)和表示完整MIME 类型字符串的type。</p>
<p>检测IE 中的插件比较麻烦，因为IE 不支持Netscape 式的插件。<br>在IE 中检测插件的唯一方式就是使用专有的ActiveXObject 类型，并尝试创建一个特定插件的实例。<br>IE 是以COM对象的方式实现插件的，而COM对象使用唯一标识符来标识。因此，要想检查特定的插件，就必须知道其COM标识符。<br>例如，Flash 的标识符是ShockwaveFlash.ShockwaveFlash。<br>知道唯一标识符之后，就可以编写函数来检测IE 中是否安装相应插件了。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//检测IE 中的插件</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasIEPlugin</span>(<span class="params">name</span>)</span>&#123;</div><div class="line">    <span class="keyword">try</span> &#123;</div><div class="line">        <span class="keyword">new</span> ActiveXObject(name);</div><div class="line">        <span class="keyword">return</span> <span class="literal">true</span>;</div><div class="line">    &#125; <span class="keyword">catch</span> (ex)&#123;</div><div class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"><span class="comment">//检测Flash</span></div><div class="line">alert(hasIEPlugin(<span class="string">"ShockwaveFlash.ShockwaveFlash"</span>));</div><div class="line"><span class="comment">//检测QuickTime</span></div><div class="line">alert(hasIEPlugin(<span class="string">"QuickTime.QuickTime"</span>));</div></pre></td></tr></table></figure>
<p>鉴于检测这两种插件的方法差别太大，因此典型的做法是针对每个插件分别创建检测函数，而不是使用前面介绍的通用检测方法。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//检测所有浏览器中的Flash</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasFlash</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> result = hasPlugin(<span class="string">"Flash"</span>);</div><div class="line">    <span class="keyword">if</span> (!result)&#123;</div><div class="line">        result = hasIEPlugin(<span class="string">"ShockwaveFlash.ShockwaveFlash"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> result;</div><div class="line">&#125;</div><div class="line"><span class="comment">//检测所有浏览器中的QuickTime</span></div><div class="line"><span class="function"><span class="keyword">function</span> <span class="title">hasQuickTime</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="keyword">var</span> result = hasPlugin(<span class="string">"QuickTime"</span>);</div><div class="line">    <span class="keyword">if</span> (!result)&#123;</div><div class="line">        result = hasIEPlugin(<span class="string">"QuickTime.QuickTime"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> result;</div><div class="line">&#125;</div><div class="line"><span class="comment">//检测Flash</span></div><div class="line">alert(hasFlash());</div><div class="line"><span class="comment">//检测QuickTime</span></div><div class="line">alert(hasQuickTime());</div></pre></td></tr></table></figure>
<p>尝试使用不针对IE 的插件检测方法。<br>如果返回了false(在IE 中会这样)，那么再使用针对IE 的插件检测方法。</p>
<p>plugins 集合有一个名叫refresh()的方法，用于刷新plugins 以反映最新安装的插件。<br>这个方法接收一个参数：表示是否应该重新加载页面的一个布尔值。如果将这个值设置为true，则会重新加载包含插件的所有页面；<br>否则，只更新plugins集合，不重新加载页面。</p>
<h3 id="注册处理程序"><a href="#注册处理程序" class="headerlink" title="注册处理程序"></a>注册处理程序</h3><p>navigator 对象新增了registerContentHandler()和registerProtocolHandler()方法(这两个方法是在HTML5 中定义的)。<br>这两个方法可以让一个站点指明它可以处理特定类型的信息。<br>随着RSS 阅读器和在线电子邮件程序的兴起，注册处理程序就为像使用桌面应用程序一样默认使用这些在线应用程序提供了一种方式。</p>
<p>registerContentHandler()方法接收三个参数：要处理的MIME 类型、可以处理该MIME类型的页面的URL 以及应用程序的名称。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">navigator.registerContentHandler(<span class="string">"application/rss+xml"</span>,</div><div class="line"><span class="string">"http://www.somereader.com?feed=%s"</span>, <span class="string">"Some Reader"</span>);</div></pre></td></tr></table></figure>
<p>第一个参数是RSS 源的MIME 类型。第二个参数是应该接收RSS 源URL 的URL，其中的%s 表示RSS 源URL，由浏览器自动插入。<br>当下一次请求RSS 源时，浏览器就会打开指定的URL，而相应的Web 应用程序将以适当方式来处理该请求。</p>
<p>registerProtocolHandler()方法，它也接收三个参数：要处理的协议(例如，mailto 或ftp)、处理该协议的页面的URL 和应用程序的名称。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">navigator.registerProtocolHandler(<span class="string">"mailto"</span>,</div><div class="line"><span class="string">"http://www.somemailclient.com?cmd=%s"</span>, <span class="string">"Some Mail Client"</span>);</div></pre></td></tr></table></figure>
<p>这个例子注册了一个mailto 协议的处理程序，该程序指向一个基于Web 的电子邮件客户端。同样，<br>第二个参数仍然是处理相应请求的URL，而%s 则表示原始的请求。</p>
<h1 id="screen-对象"><a href="#screen-对象" class="headerlink" title="screen 对象"></a>screen 对象</h1><p>JavaScript 中有几个对象在编程中用处不大，而screen 对象就是其中之一。<br>screen 对象基本上只用来表明客户端的能力，其中包括浏览器窗口外部的显示器的信息，如像素宽度和高度等。<br>这些信息经常集中出现在测定客户端能力的站点跟踪工具中，但通常不会用于影响功能。<br>有时候也可能会用到其中的信息来调整浏览器窗口大小，使其占据屏幕的可用空间。<br>例如：<code>window.resizeTo(screen.availWidth, screen.availHeight);</code><br>许多浏览器都会禁用调整浏览器窗口大小的能力，因此上面这行代码不一定在所有环境下都有效。</p>
<p>涉及移动设备的屏幕大小时，情况有点不一样。<br>运行iOS 的设备始终会像是把设备竖着拿在手里一样，因此返回的值是768×1024。<br>而Android 设备则会相应调用screen.width 和screen.height 的值。</p>
<h1 id="history-对象"><a href="#history-对象" class="headerlink" title="history 对象"></a>history 对象</h1><p>history 对象保存着用户上网的历史记录，从窗口被打开的那一刻算起。<br>因为history 是window对象的属性，因此每个浏览器窗口、每个标签页乃至每个框架，都有自己的history 对象与特定的window 对象关联。<br>出于安全方面的考虑，开发人员无法得知用户浏览过的URL。<br>不过，借由用户访问过的页面列表，同样可以在不知道实际URL 的情况下实现后退和前进。<br>使用go()方法可以在用户的历史记录中任意跳转，可以向后也可以向前。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//后退一页</span></div><div class="line">history.go(<span class="number">-1</span>);</div><div class="line"><span class="comment">//前进一页</span></div><div class="line">history.go(<span class="number">1</span>);</div><div class="line"><span class="comment">//前进两页</span></div><div class="line">history.go(<span class="number">2</span>);</div></pre></td></tr></table></figure>
<p>也可以给go()方法传递一个字符串参数，此时浏览器会跳转到历史记录中包含该字符串的第一个位置——可能后退，也可能前进，具体要看哪个位置最近。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//跳转到最近的wrox.com 页面</span></div><div class="line">history.go(<span class="string">"wrox.com"</span>);</div><div class="line"><span class="comment">//跳转到最近的nczonline.net 页面</span></div><div class="line">history.go(<span class="string">"nczonline.net"</span>);</div></pre></td></tr></table></figure>
<p>还可以使用两个简写方法back()和forward()来代替go()。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//后退一页</span></div><div class="line">history.back();</div><div class="line"><span class="comment">//前进一页</span></div><div class="line">history.forward();</div></pre></td></tr></table></figure>
<p>history 对象还有一个length 属性，保存着历史记录的数量。<br>对于加载到窗口、标签页或框架中的第一个页面而言，history.length 等于0。<br>(所以类似百度这种网站，弹出“是否设为主页”的这种判断是不是利用length 等于0?)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (history.length == <span class="number">0</span>)&#123;</div><div class="line">    <span class="comment">//这应该是用户打开窗口后的第一个页面</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>当页面的URL 改变时，就会生成一条历史记录。<br>在IE8 及更高版本、Opera、Firefox、Safari 3 及更高版本以及Chrome 中，<br>这里所说的改变包括URL 中hash 的变化(因此，设置location.hash 会在这些浏览器中生成一条新的历史记录)。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/09/30/javascript-note-09-1/" rel="next" title="《 JavaScript 高级程序设计》备忘-第九章-1">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第九章-1
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/02/javascript-note-09-2/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第九章-2">
                《 JavaScript 高级程序设计》备忘-第九章-2 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Location-对象"><span class="nav-number">1.</span> <span class="nav-text">Location 对象</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#查询字符串参数"><span class="nav-number">1.1.</span> <span class="nav-text">查询字符串参数</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#位置操作"><span class="nav-number">1.2.</span> <span class="nav-text">位置操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#navigator-对象"><span class="nav-number">1.3.</span> <span class="nav-text">navigator 对象</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#检测插件"><span class="nav-number">1.3.1.</span> <span class="nav-text">检测插件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#注册处理程序"><span class="nav-number">1.3.2.</span> <span class="nav-text">注册处理程序</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#screen-对象"><span class="nav-number">2.</span> <span class="nav-text">screen 对象</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#history-对象"><span class="nav-number">3.</span> <span class="nav-text">history 对象</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
